﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using Shell.DomainDot;
using Framework.Poco;
using Framework.Domain;

namespace Framework.Mvc.Controllers
{
    public class UserController : Controller
    {
        private IDomainDotFactory factory;

        public UserController()
        {
            factory = DomainDotFactory.Factory;
        }

        [HttpGet]
        public ActionResult Register()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Register(UserRegisterViewModel model)
        {
            try
            {
                if (!Valid(this.ModelState, model.Instance) || !Valid(this.ModelState, model.Contact))
                {
                    return View(model);
                }
                var context = factory.Create<UserRegisterContext>();
                context.Register(model.Instance, model.Contact);
                return this.RedirectToAction("Index", "Home");
            }
            catch
            {
                return View();
            }
        }

        private bool Valid(ModelStateDictionary state, User instance)
        {
            var isValid = true;
            if (instance == null)
            {
                state.AddModelError("Instance", "用户不能为空!");
                isValid = false;
            }
            if (string.IsNullOrWhiteSpace(instance.Name))
            {
                state.AddModelError("Name", "用户名为空!");
                isValid = false;
            }
            if (string.IsNullOrWhiteSpace(instance.Password))
            {
                state.AddModelError("Password", "密码不能为空或者null");
                isValid = false;
            }
            if (string.IsNullOrWhiteSpace(instance.DisplayName))
            {
                state.AddModelError("DisplayName", "新人姓名不能为空");
                isValid = false;
            }
            return isValid;
        }

        private bool Valid(ModelStateDictionary state, Contact contact)
        {
            var isValid = true;
            if (string.IsNullOrWhiteSpace(contact.Mobile))
            {
                state.AddModelError("Mobile", "请输入您的手机号!");
                isValid = false;
            }
            if (string.IsNullOrWhiteSpace(contact.QQ) && string.IsNullOrWhiteSpace(contact.MSN))
            {
                state.AddModelError("QQ", "QQ为空!");
                state.AddModelError("MSN", "MSN为空!");
                isValid = false;
            }
            return isValid;
        }
    }
}
